"undefined"==typeof Event&&(Event={});Event.Keys||(Event.Keys={up:38,down:40,enter:13,left:37,right:39,"delete":46,backspace:8});
var TextboxList=new Class({Implements:[Options,Events],plugins:[],options:{prefix:"textboxlist",max:null,unique:!0,uniqueInsensitive:!0,endEditableBit:!0,startEditableBit:!0,hideEditableBits:!0,inBetweenEditableBits:!0,keys:{previous:Event.Keys.left,next:Event.Keys.right},bitsOptions:{editable:{},box:{}},plugins:{},check:function(a){return""!=a.clean().replace(/,/g,"")},encode:function(a){return a.map(function(a){a=null!=a[0]?a[0]:a[1];return null!=a?a:null}).clean().join("|")},decode:function(a){return a.split("|")}},
initialize:function(a,b){this.setOptions(b);$(a).textbox=this;this.original=$(a).setStyle("display","none").set("autocomplete","off").addEvent("focus",this.focusLast.bind(this));this.container=(new Element("div",{"class":this.options.prefix})).inject(a,"after");this.container.addEvent("click",function(a){a.target!=this.list&&a.target!=this.container||this.focused&&$(this.current)==this.list.getLast()||this.focusLast()}.bind(this));this.list=(new Element("ul",{"class":this.options.prefix+"-bits"})).inject(this.container);
for(var c in this.options.plugins)this.enablePlugin(c,this.options.plugins[c]);["check","encode","decode"].each(function(a){this.options[a]=this.options[a].bind(this)},this);this.afterInit();var d=$(a).getParent("form");d&&""!=d.get("action")&&d.getElement('input[type="submit"]').addEvent("click",function(a){d.getElements(".sr-list").set("cached",null);d.getElements(".sr-list .inner").set("html","");d.getElements(".textboxlist-autocomplete-selwinhandler").removeClass("active");d.fade(0.6);d.spinner||
(d.getElements(".sr-list").each(function(a){(new Fx.Morph(a,{onStart:function(){a.setStyle("overflowy","hidden")},onComplete:function(){},duration:50,link:"chain"})).start({height:0,"margin-bottom":0,"margin-top":0})}),d.spinner=new Spinner(d,{"class":"formspinner"}),function(){d.spinner.show()}.delay(100))})},enablePlugin:function(a,b){this.plugins[a]=new (TextboxList[a.camelCase().capitalize()])(this,b)},afterInit:function(){this.options.unique&&(this.index=[]);this.options.endEditableBit&&this.create("editable",
null,{tabIndex:this.original.tabIndex}).inject(this.list);var a=this.update.bind(this);this.addEvent("bitAdd",a,!0).addEvent("bitRemove",a,!0);document.addEvents({click:function(a){this.focused&&(!a.target.className.contains(this.options.prefix)||a.target!=this.container&&a.target.getParent("."+this.options.prefix)!=this.container)&&this.blur()}.bind(this),keydown:function(a){if(this.focused&&this.current){var c=this.current.is("editable")?this.current.getCaret():null,d=this.current.getValue()[1],
e=["shift","alt","meta","ctrl"].some(function(c){return a[c]})||this.current.is("editable")&&this.current.isSelected();switch(a.code){case Event.Keys.backspace:if(this.current.is("box"))return a.stop(),this.current.remove(),!1;break;case this.options.keys.previous:if(this.current.is("box")||!(0!=c&&d.length||e))a.stop(),this.focusRelative("previous");break;case Event.Keys["delete"]:if(this.current.is("box"))return a.stop(),this.current.remove(),!1;break;case this.options.keys.next:if(this.current.is("box")||
c==d.length&&!e)a.stop(),this.focusRelative("next")}}}.bind(this)});this.setValues(this.options.decode(this.original.get("value")));this.resetToValues=this.getValues()},create:function(a,b,c){return"box"==a&&(!b[0]&&!b[1]||null!=b[1]&&!this.options.check(b[1])||null!=this.options.max&&this.list.getChildren("."+this.options.prefix+"-bit-box").length+1>this.options.max||this.options.unique&&this.index.contains(this.uniqueValue(b)))?!1:new (TextboxListBit[a.capitalize()])(b,this,Object.merge(this.options.bitsOptions[a],
c))},uniqueValue:function(a){return ret=null!=a[0]?this.options.uniqueInsensitive?a[0].toLowerCase():a[0]:this.options.uniqueInsensitive?a[1].toLowerCase():a[1]},onFocus:function(a){this.current&&this.current.blur();clearTimeout(this.blurtimer);this.current=a;this.container.addClass(this.options.prefix+"-focus");this.focused||(this.focused=!0,this.fireEvent("focus",a))},onBlur:function(a,b){this.current=null;this.container.removeClass(this.options.prefix+"-focus");this.blurtimer=this.blur.delay(b?
0:200,this)},onAdd:function(a){if(a&&(a.value&&a.value[1]&&this.container.getNext("div.sr-list").getElements('input[type="checkbox"]').each(function(b,d){b.get("value")==a.value[1]&&b.set("checked",!0)}),this.options.unique&&a.is("box")&&this.index.push(this.uniqueValue(a.value)),a.is("box"))){var b=this.getBit($(a).getPrevious());if(b&&b.is("box")&&this.options.inBetweenEditableBits||!b&&this.options.startEditableBit)b=this.create("editable").inject(b||this.list,b?"after":"top"),this.options.hideEditableBits&&
b.hide()}},onRemove:function(a){a.value&&a.value[1]&&this.container.getNext("div.sr-list").getElements('input[type="checkbox"]').each(function(b,d){b.get("value")==a.value[1]&&b.set("checked",!1)});if(this.focused){this.options.unique&&a.is("box")&&this.index.erase(this.uniqueValue(a.value));var b=this.getBit($(a).getPrevious());b&&b.is("editable")&&b.remove();this.focusRelative("next",a)}},focusRelative:function(a,b){var c=[b,this.current].pick();(c=this.getBit($(c)["get"+a.capitalize()]()))&&c.focus();
return this},focusLast:function(){var a=this.list.getLast();a&&this.getBit(a).focus();return this},blur:function(){if(!this.focused)return this;this.current&&this.current.blur();this.focused=!1;return this.fireEvent("blur")},add:function(a,b,c,d){if(a=this.create("box",[b,a,c]))d||(d=this.list.getLast("."+this.options.prefix+"-bit-box")),a.inject(d||this.list,d?"after":"top");return this},getBit:function(a){return a&&a.retrieve?"element"==typeOf(a)?a.retrieve("textboxlist:bit"):a:a},getValues:function(){return values=
this.list.getChildren().map(function(a){a=this.getBit(a);return!a||a.is("editable")?null:a.getValue()},this).clean()},setValues:function(a){a&&0!=a.length?a.each(function(a){a&&this.add.apply(this,"array"==typeOf(a)?[a[1],a[0],a[2]]:[a])},this):this.clearValues()},resetValues:function(){this.index=[];this.clearValues();this.setValues(this.resetToValues)},clearValues:function(){this.original.set("value","");this.index=[];return this.list.getChildren().map(function(a){(a=this.getBit(a))&&(a.is("editable")||
a.remove())},this)},update:function(){this.original.set("value",this.options.encode(this.getValues()))}}),TextboxListBit=new Class({Implements:Options,initialize:function(a,b,c){this.name=this.type.capitalize();this.value=a;this.textboxlist=b;this.setOptions(c);this.prefix=this.textboxlist.options.prefix+"-bit";this.typeprefix=this.prefix+"-"+this.type;this.bit=(new Element("li")).addClass(this.prefix).addClass(this.typeprefix).store("textboxlist:bit",this);this.bit.addEvents({mouseenter:function(){this.bit.addClass(this.prefix+
"-hover").addClass(this.typeprefix+"-hover")}.bind(this),mouseleave:function(){this.bit.removeClass(this.prefix+"-hover").removeClass(this.typeprefix+"-hover")}.bind(this)})},inject:function(a,b){this.bit.inject(a,b);this.textboxlist.onAdd(this);return this.fireBitEvent("add")},focus:function(){if(this.focused)return this;this.show();this.focused=!0;this.textboxlist.onFocus(this);this.bit.addClass(this.prefix+"-focus").addClass(this.prefix+"-"+this.type+"-focus");return this.fireBitEvent("focus")},
blur:function(){if(!this.focused)return this;this.focused=!1;this.textboxlist.onBlur(this);this.bit.removeClass(this.prefix+"-focus").removeClass(this.prefix+"-"+this.type+"-focus");return this.fireBitEvent("blur")},remove:function(){this.blur();this.bit.destroy();if(!Browser.ie8&&!Browser.ie7)this.textboxlist.onRemove(this);return this.fireBitEvent("remove")},show:function(){this.bit.setStyle("display","block");return this},hide:function(){this.bit.setStyle("display","none");return this},fireBitEvent:function(a){a=
a.capitalize();this.textboxlist.fireEvent("bit"+a,this).fireEvent("bit"+this.name+a,this);return this},is:function(a){return this.type==a},setValue:function(a){this.value=a;return this},getValue:function(){return this.value},toElement:function(){return this.bit}});
TextboxListBit.Editable=new Class({Extends:TextboxListBit,options:{tabIndex:null,growing:!0,growingOptions:{},stopEnter:!0,addOnBlur:!1,addKeys:["|",";"]},type:"editable",initialize:function(a,b,c){this.parent(a,b,c);this.element=(new Element("input",{type:"text","class":this.typeprefix+"-input",autocomplete:"off",value:this.value?this.value[1]:""})).inject(this.bit);null!=this.options.tabIndex&&(this.element.tabIndex=this.options.tabIndex);this.options.growing&&new GrowingInput(this.element,this.options.growingOptions);
this.element.addEvents({focus:function(){this.focus(!0)}.bind(this),blur:function(){this.blur(!0);this.options.addOnBlur&&this.toBox()}.bind(this)});(this.options.addKeys||this.options.stopEnter)&&this.element.addEvent("keypress",function(a){if(this.focused){var b=a.which||a.keyCode||a.code,c=String.fromCharCode(b);this.options.stopEnter&&b===Event.Keys.enter&&a.stop();Array.from(this.options.addKeys).contains(c)&&(a.stop(),this.toBox())}}.bind(this))},hide:function(){this.parent();this.hidden=!0;
return this},focus:function(a){this.parent();a||this.element.focus();return this},blur:function(a){this.parent();a||this.element.blur();this.hidden&&!this.element.value.length&&this.hide();return this},getCaret:function(){if(this.element.createTextRange){var a=document.selection.createRange().duplicate();a.moveEnd("character",this.element.value.length);return""===a.text?this.element.value.length:this.element.value.lastIndexOf(a.text)}return this.element.selectionStart},getCaretEnd:function(){if(this.element.createTextRange){var a=
document.selection.createRange().duplicate();a.moveStart("character",-this.element.value.length);return a.text.length}return this.element.selectionEnd},isSelected:function(){return this.focused&&this.getCaret()!==this.getCaretEnd()},setValue:function(a){this.element.value=null!=a[0]?a[0]:a[1];this.options.growing&&this.element.retrieve("growing").resize();return this},getValue:function(){return[null,this.element.value,null]},toBox:function(){var a=this.getValue();return(a=this.textboxlist.create("box",
a))?(a.inject(this.bit,"before"),this.setValue([null,"",null]),a):null}});
TextboxListBit.Box=new Class({Extends:TextboxListBit,options:{deleteButton:!0},type:"box",initialize:function(a,b,c){this.parent(a,b,c);this.bit.set("html",null!=this.value[2]?this.value[2]:this.value[1]);this.bit.addEvent("click",this.focus.bind(this));this.options.deleteButton&&(this.bit.addClass(this.typeprefix+"-deletable"),this.close=(new Element("a",{href:"javascript:void(0)","class":this.typeprefix+"-deletebutton",events:{click:this.remove.bind(this)}})).inject(this.bit));this.bit.getChildren().addEvent("click",
function(a){a.stop()})}});
(function(){TextboxList.Autocomplete=new Class({Implements:Options,options:{selWinCols:"",minLength:2,maxResults:100,insensitive:!0,highlight:!0,highlightSelector:null,mouseInteraction:!0,onlyFromValues:!0,queryRemote:!1,selWindow:!0,remote:{url:"",param:"search",extraParams:{},loadPlaceholder:"Please wait..."},method:"standard",placeholder:"Введите минимум два символа для загрузки списка",emptyPlaceholder:"Не найдено значений, начинающихся на {$search}"},initialize:function(a,b){this.setOptions(b);
this.textboxlist=a;this.textboxlist.addEvent("bitEditableAdd",this.setupBit.bind(this),!0).addEvent("bitEditableFocus",this.search.bind(this),!0).addEvent("bitEditableBlur",this.hide.bind(this),!0);Browser.ie&&this.textboxlist.setOptions({bitsOptions:{editable:{addOnBlur:!1}}});this.textboxlist.options.unique&&(this.index=[],this.textboxlist.addEvent("bitBoxRemove",function(a){a.autoValue&&this.index.erase(a.autoValue)}.bind(this),!0));this.prefix=this.textboxlist.options.prefix+"-autocomplete";this.method=
TextboxList.Autocomplete.Methods[this.options.method];this.container=(new Element("div",{"class":this.prefix})).setStyle("width",this.textboxlist.original.getDimensions().x).inject(this.textboxlist.container,"after");if(null!=this.options.placeholder||this.options.queryServer)this.placeholder=(new Element("div",{"class":this.prefix+"-placeholder"})).inject(this.container);this.list=(new Element("ul",{"class":this.prefix+"-results"})).inject(this.container);this.list.addEvent("click",function(a){a.stop()});
this.values=this.results=this.searchValues=[];this.navigate=this.navigate.bind(this);this.options.selWindow&&(this.selWinHandler=(new Element("div",{"class":this.prefix+"-selwinhandler"})).inject(this.textboxlist.container),this.selWinHandler.addEvent("click",function(a){a.target.toggleClass("active");this.showSelWindow(this)}.bind(this),!0));document.helpshown=!1},showSelWindow:function(a){var b=this;this.divList=this.textboxlist.original.getParent("td").getElement("div.sr-list");"1"==this.divList.getAttribute("listVisible")?
(this.divList.setAttribute("listVisible","0"),this.hideSelWindow()):1==b.divList.get("cached")?b.adjustSelWindow(b.divList):(a=this.options.remote.extraParams,a.currentlyselected=this.textboxlist.original.get("value"),this.currentRequestSel&&this.currentRequestSel.cancel(),(new Fx.Morph(b.divList,{duration:300,link:"cancel"})).start({height:50,"margin-bottom":0,"margin-top":8}),this.currentRequestSel=(new Request.JSON({url:this.options.remote.url.replace("autocompleter","autocompletersel"),data:a,
onRequest:function(){b.divList.setStyle("display","block").addClass("loading")},onSuccess:function(a){b.divList.set("cached",1);b.divList.removeClass("loading");b.selwinres=a;b.showSelWindowResults();b.adjustSelWindow(b.divList)}})).send())},adjustSelWindow:function(a){a.setAttribute("listVisible","1");__area=a.getElement("div.inner");(new Fx.Morph(this.divList,{onStart:function(){},onComplete:function(){a.setStyle("overflow-y","auto")},duration:300,link:"chain"})).start({display:"block",height:Math.min(315,
__area.getDimensions().y+17),"margin-bottom":0,"margin-top":8})},decodeCB:function(a){return(new Element("div")).set("html",a).get("text")+""},submitSelWindow:function(a){var b=[];this.divList.getElement("div.inner").getElements(".cb").each(function(a,d){a.get("checked")&&b.push(a.get("value"))});this.textboxlist.setValues();this.textboxlist.setValues(b)},showSelWindowResults:function(){var a=this;__object=this.divList;__area=__object.getElement("div.inner").addClass(a.options.selWinCols);__area.set("html",
"");var b=[];this.textboxlist.getValues().each(function(a,c){b.push(a[1])});this.selwinres.each(function(c,e){var f=b.contains(c[1]),g=a.textboxlist.original.get("name"),h=(new Element("div",{"class":"selbit"})).inject(__area),k=(new Element("input",{"class":"cb",type:"checkbox",value:a.decodeCB(c[1]),id:"selwincb"+e+g,name:"selwincb"+e+g})).inject(h);(new Element("label",{"for":"selwincb"+e+g,text:a.decodeCB(c[1])})).inject(h);f&&k.set("checked","checked")});(new Element("div",{"class":"clr"})).inject(__area);
var c=function(){this.submitSelWindow(this)}.bind(this);__area.getElements('input[type="checkbox"]').addEvent("change",c)},hideSelWindow:function(){that=this;(new Fx.Morph(this.divList,{onStart:function(){that.divList.setStyle("overflow-y","hidden")},onComplete:function(){},duration:300,link:"chain"})).start({height:0,"margin-bottom":0,"margin-top":0})},setValues:function(a){this.values=a},setupBit:function(a){a.element.addEvent("keydown",this.navigate,!0).addEvent("keyup",function(){this.search()}.bind(this),
!0)},search:function(a){a&&(this.currentInput=a);if(this.options.queryRemote||this.values.length){a=this.textboxlist.original.getParent("td").getElement("div.sr-list");var b=this.currentInput.getValue()[1];if("1"==a.getAttribute("listVisible")){var c=this.textboxlist.container.getElements('input[type="text"]'),c=c[c.length-1].get("value"),d=null,c=a.getElements('input[type="checkbox"]');for(i=0;i<c.length;i++)if(console.log(b+" [ ] "+c[i].get("value")+" = "+c[i].get("value").search(eval("/^"+b+"/i"))),
0===c[i].get("value").search(eval("/^"+b+"/i"))){d=c[i];break}if(d&&0<b.length){try{this.oldEl.setStyle("")}catch(e){}d.getParent("div");(new Fx.Scroll(a,{duration:100,wait:!1,onComplete:function(){(new Fx.Morph(d.getParent("div"),{duration:400,link:"chain"})).set({"background-color":"#fcefa1"}).start({"background-color":"#f5f5ea"})}})).toElement(d)}else 0==b.length&&(new Fx.Scroll(a,{duration:300,wait:!1})).toTop()}else if(b.length<this.options.minLength&&!document.helpshown&&(document.helpshown=
!0,this.showPlaceholder(this.options.placeholder)),this.currentSearch=b,this.list.setStyle("display","none"),!(b.length<this.options.minLength))if(this.options.queryRemote)if(this.searchValues[b])this.values=this.searchValues[b],this.values.length&&this.showResults(b);else{a=this.options.remote.extraParams;var f=this;"function"==typeOf(a)&&(a=a.run([],this));a[this.options.remote.param]=b;this.currentRequest&&this.currentRequest.cancel();this.currentRequest=(new Request.JSON({url:this.options.remote.url,
data:a,onRequest:function(){f.showPlaceholder(f.options.remote.loadPlaceholder)},onSuccess:function(a){f.searchValues[b]=a;f.values=a;f.showResults(b)}})).send()}else this.values.length&&this.showResults(b)}},addResult:function(a,b){var c=(new Element("li",{"class":this.prefix+"-result",html:[a[3],a[1]].pick()})).store("textboxlist:auto:value",a);this.list.adopt(c);this.options.highlight&&$$(this.options.highlightSelector?c.getElements(this.options.highlightSelector):c).each(function(a){a.get("html")&&
this.method.highlight(a,b,this.options.insensitive,this.prefix+"-highlight")},this);this.options.mouseInteraction&&(c.setStyle("cursor","pointer").addEvents({mouseenter:function(){this.focus(c)}.bind(this),mousedown:function(a){a.stop();clearTimeout(this.hidetimer);this.doAdd=!0}.bind(this),mouseup:function(){this.doAdd&&(this.addCurrent(),this.currentInput.focus(),this.search(),this.doAdd=!1)}.bind(this)}),this.options.onlyFromValues||c.addEvent("mouseleave",function(){this.current==c&&this.blur()}.bind(this)))},
hide:function(a){this.hidetimer=function(){this.hidePlaceholder();this.list.setStyle("display","none");this.currentSearch=null}.delay(Browser.ie?150:0,this)},showResults:function(a){var b=this.method.filter(this.values,a,this.options.insensitive,this.options.maxResults);this.index&&(b=b.filter(function(a){return!this.index.contains(a)},this));this.hidePlaceholder();b.length&&(this.blur(),this.list.empty().setStyle("display","block"),b.each(function(b){this.addResult(b,a)},this),this.options.onlyFromValues&&
this.focusFirst(),this.results=b,this.list.setStyle("width",this.container.getSize().x-6))},showPlaceholder:function(a){this.placeholder&&(this.placeholder.setStyle("display","block"),a&&this.placeholder.set("html",a),this.placeholder.setStyle("width",this.container.getSize().x-12))},hidePlaceholder:function(){this.placeholder&&this.placeholder.setStyle("display","none")},focus:function(a){if(!a)return this;this.blur();this.current=a.addClass(this.prefix+"-result-focus")},blur:function(){this.current&&
(this.current.removeClass(this.prefix+"-result-focus"),this.current=null)},focusFirst:function(){return this.focus(this.list.getFirst())},focusRelative:function(a){return this.current?this.focus(this.current["get"+a.capitalize()]()):this},addCurrent:function(){if(this.current){var a=this.current.retrieve("textboxlist:auto:value"),b=this.textboxlist.create("box",a.slice(0,3));b&&(b.autoValue=a,null!=this.index&&this.index.push(a),this.currentInput.setValue([null,"",null]),b.inject($(this.currentInput),
"before"));this.blur();return this}},navigate:function(a){if("block"!=this.placeholder.getStyle("display"))switch(a.code){case Event.Keys.up:a.stop();!this.options.onlyFromValues&&this.current&&this.current==this.list.getFirst()?this.blur():this.focusRelative("previous");break;case Event.Keys.down:a.stop();this.current?this.focusRelative("next"):this.focusFirst();break;case Event.Keys.enter:(a.stop(),this.current)?this.addCurrent():!this.options.onlyFromValues&&(a=this.currentInput.getValue(),a=this.textboxlist.create("box",
a))&&(a.inject($(this.currentInput),"before"),this.currentInput.setValue([null,"",null]))}}});TextboxList.Autocomplete.Methods={standard:{filter:function(a,b,c,d){c=[];b.escapeRegExp();for(b=0;b<a.length&&c.length!==d;b++)c.push(a[b]);return c},highlight:function(a,b,c,d){b=RegExp("("+b.escapeRegExp()+")",c?"i":"");return a.set("html",a.get("html").replace(b,function(a,b,c){return'<strong class="'+d+'">'+b+"</strong>"}))}}}})();
(function(){GrowingInput=new Class({Implements:[Options,Events],options:{min:0,max:null,startWidth:2,correction:15},initialize:function(a,c){this.setOptions(c);this.element=$(a).store("growing",this).set("autocomplete","off");this.calc=(new Element("span",{styles:{"float":"left",display:"inline-block",position:"absolute",left:-1E3}})).inject(this.element,"after");"font-size font-family padding-left padding-top padding-bottom padding-right border-left border-right border-top border-bottom word-spacing letter-spacing text-indent text-transform".split(" ").each(function(a){this.calc.setStyle(a,
this.element.getStyle(a))},this);this.resize();var d=this.resize.bind(this);this.element.addEvents({blur:d,keyup:d,keydown:d,keypress:d})},calculate:function(a){this.calc.set("html",a);a=this.calc.getStyle("width").toInt();return(a?a:this.options.startWidth)+this.options.correction},resize:function(){this.lastvalue=this.value;var b=this.value=this.element.value;if(null!=this.options.min&&this.value.length<this.options.min){if(null!=this.lastvalue&&this.lastvalue.length<=this.options.min)return;b=
a(this.value,this.options.min,"-")}else if(null!=this.options.max&&this.value.length>this.options.max){if(null!=this.lastvalue&&this.lastvalue.length>=this.options.max)return;b=this.value.substr(0,this.options.max)}this.element.setStyle("width",this.calculate(b));return this}});var a=function(a,c,d,e){if(a.length>=c)return this;c=Array(c-a.length+1).join(d||" ").substr(0,c-a.length);return e&&"right"!=e?"left"==e?c+a:c.substr(0,(c.length/2).floor())+a+c.substr(0,(c.length/2).ceil()):a+c}})();
